from django.shortcuts import render, render_to_response
from django.http import HttpResponse
from django.shortcuts import render
from django.db import connection
import json
from flask import jsonify
import time
import datetime
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from .models import UserInfo,packageInfo,SchemeInfo,PayLog,used_log,user_package,AppointInfo,position_room,teacher_img,position_img,user_base,NewPayLog
from django.utils.timezone import now, timedelta
import re
from django.core import serializers

@csrf_exempt
def home(request):
    if request.method == 'POST':
        next_url = request.POST.get('url')
    else:
        next_url = request.GET.get('url')
    c={
        'next_url':next_url,
    }
    return render_to_response('home.html',c)

# 返回class_list页面
def class_list(request):
    open_id = request.GET.get('openId')
    nickName = request.GET.get('nickName')
    headImgUrl = request.GET.get('headImgUrl')

    queryset = UserInfo.objects.filter(open_id=open_id)
    if queryset.exists():
        if nickName != None:
            if queryset.first().nickname != nickName:
                queryset.update(nickname=nickName,update_time=datetime.datetime.now())
        if headImgUrl != None:
            if queryset.first().avatar != headImgUrl:
                queryset.update(avatar=headImgUrl,update_time=datetime.datetime.now())
        user_id = queryset.first().user_id
        nickName = queryset.first().nickname
        headImgUrl = queryset.first().avatar
    else:
        queryset = UserInfo.objects.create(
            open_id=open_id,
            avatar=headImgUrl,
            nickname=nickName
        )
        user_id = queryset.user_id
    c = {
        'open_id':open_id,
        'user_id':user_id
    }
    
    return render_to_response('class_list.html',c)

# class_list页面自动或者手动获取两天信息
@csrf_exempt
def get_day_list(request):
    if request.method == 'POST':
        idx = request.POST.get('idx')
        open_id = request.POST.get('open_id')
        scheme_type = request.POST.get('scheme_type')
        is_first = request.POST.get('isfirst')
    else:
        idx = request.GET.get('idx')
        open_id = request.GET.get('open_id')
        scheme_type = request.GET.get('scheme_type')
        is_first = request.GET.get('isfirst')

    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    today = now().date() + timedelta(days=(2*int(idx)))
    tomorrow = today + timedelta(days=2)
    if int(scheme_type) == 3:
        if is_first == str(1):
            
            stoday = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
            queryset = SchemeInfo.objects.filter(start_time__gte=stoday,start_time__lte=tomorrow,state=1).all().order_by("start_time")
        else:
            
            queryset = SchemeInfo.objects.filter(start_time__gte=today,start_time__lte=tomorrow,state=1).all().order_by("start_time")
    else:
        queryset = SchemeInfo.objects.filter(start_time__gte=today,start_time__lte=tomorrow,scheme_type=scheme_type,state=1).all().order_by("start_time")
    a_json=[]
    double_json=[]
    center = (today + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
    center_tmp = (today + timedelta(days=1))
    center = center_tmp.strftime('%Y-%m-%d %H:%M:%S')
    for query in queryset:
        shijian = query.start_time.strftime('%Y-%m-%d %H:%M:%S')
        if shijian > center:
            double_json.append(a_json)
            # center = tomorrow.strftime('%Y-%m-%d')
            center_tmp = center_tmp + timedelta(days=1)
            center = center_tmp.strftime('%Y-%m-%d %H:%M:%S')
            a_json=[]
        user_name = UserInfo.objects.filter(user_id=(query.user_id)).first().real_name
        num = AppointInfo.objects.filter(scheme_id=(query.scheme_id),status=1).count()
        day = int(time.mktime(query.start_time.timetuple()))

        yuyue = AppointInfo.objects.filter(user_id=user_id,scheme_id=(query.scheme_id),status=1)
        isyueyue = 0
        if yuyue.exists():
            isyueyue = 1
        position = position_room.objects.filter(position_room_id=query.position).first().position_room_name
        a_json.append({
            "day":day,
            "scheme_id":query.scheme_id,
            "scheme_name":query.scheme_name,
            "user_name":user_name,
            'now_people':num,
            "max_people":query.max_people,
            "isyuyue":isyueyue,
            "position":position,
            "type":query.scheme_type
        })
    double_json.append(a_json)
    return HttpResponse(json.dumps(double_json),content_type="application/json")

def my_info(request):
    open_id = request.GET.get('open_id');
    query = UserInfo.objects.filter(open_id=open_id).first()
    user_id = query.user_id

    real_name = query.real_name
    tel = query.tel

    c = {
        'open_id':open_id,
        'user_id':user_id,
        'real_name':real_name,
        'tel':tel
    }

    return render_to_response('my_info.html',c)

def xiugai_my_info(request):
    open_id = request.GET.get('open_id');
    status = request.GET.get('status');
    query = UserInfo.objects.filter(open_id=open_id).first()

    user_id = query.user_id
    c = {
        'open_id':open_id,
        'user_id':user_id,
        'status':status,
    }
    return render_to_response('xiugai_my_info.html',c)

@csrf_exempt
def xiugai_info(request):
    open_id = request.POST.get('open_id')
    real_name = request.POST.get('real_name')
    tel = request.POST.get('tel')
    query = UserInfo.objects.filter(open_id=open_id).update(real_name=real_name,tel=tel,update_time=datetime.datetime.now())
    return HttpResponse("true")


# 返回课程详情页面 
def class_detail(request):
    class_id = request.GET.get('class_id');
    open_id = request.GET.get('open_id');
    query = UserInfo.objects.filter(open_id=open_id).first()
    user_id = query.user_id
    nickname = query.nickname
    headImgUrl = query.avatar

    yuyue = AppointInfo.objects.filter(user_id=user_id,scheme_id=class_id,status=1)
    if yuyue.exists():
        queryset = SchemeInfo.objects.filter(scheme_id=class_id,state=1).first()

        position = position_room.objects.filter(position_room_id=queryset.position).first().position_room_name
        c = {
            'cores':queryset,
            'class_id':class_id,
            'user_id':user_id,
            'open_id':open_id,
            'position':position,
            'nickname':nickname,
            'headImgUrl':headImgUrl
        }
        return render_to_response('saoma.html',c)

    queryset = SchemeInfo.objects.filter(scheme_id=class_id,state=1).first()
    position = position_room.objects.filter(position_room_id=queryset.position).first().position_room_name
    teacher_id = queryset.user_id
    teacher = UserInfo.objects.filter(user_id=teacher_id).first()
    teacher_name = teacher.real_name
    tea_img = teacher_img.objects.filter(user_id=teacher_id).first().img_url
    day = int(time.mktime(queryset.start_time.timetuple()))
    c = {
        'cores':queryset,
        'class_id':class_id,
        'user_id':user_id,
        'position':position,
        'teacher_name':teacher_name,
        'teacher_id':teacher_id,
        'open_id':open_id,
        'day':day,
        'teacher_img':tea_img
    }
    return render_to_response('class_detail.html',c)

def user_agree(request):
    return render_to_response('user_agree.html')
# 返回套餐卡列表
def package_list(request):
    open_id = request.GET.get('openId')
    nickName = request.GET.get('nickName')
    headImgUrl = request.GET.get('headImgUrl')
    queryset = UserInfo.objects.filter(open_id=open_id)
    if queryset.exists():
        if nickName != None:
            if queryset.first().nickname != nickName:
                queryset.update(nickname=nickName,update_time=datetime.datetime.now())
        if headImgUrl != None:
            if queryset.first().avatar != headImgUrl:
                queryset.update(avatar=headImgUrl,update_time=datetime.datetime.now())
        user_id = queryset.first().user_id
        nickName = queryset.first().nickname
        headImgUrl = queryset.first().avatar
    else:
        queryset = UserInfo.objects.create(
            open_id=open_id,
            avatar=headImgUrl,
            nickname=nickName
        )
        user_id = queryset.user_id

    queryset = packageInfo.objects.filter(status=1,state=1,price__gt=1).all().order_by("price")

    c = {
        'cores':queryset,
        'open_id':open_id,
        'user_id':user_id,
        'nickName':nickName,
        'headImgUrl':headImgUrl,
    }
    return render_to_response('package_list.html',c)

# 返回套餐卡详情
def package_detail(request):
    open_id = request.GET.get('open_id')
    package_id = request.GET.get('package_id')
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    queryset = packageInfo.objects.filter(package_id=package_id).first()
    c = {
        'cores':queryset,
        'user_id':user_id,
        'open_id':open_id,
        'package_id':package_id
    }
    return render_to_response('package_detail.html',c)

# 团课试课
def trial_card_t(request):
    open_id = request.GET.get('openId')
    nickName = request.GET.get('nickName')
    headImgUrl = request.GET.get('headImgUrl')
    queryset = UserInfo.objects.filter(open_id=open_id)
    if queryset.exists():
        if nickName != None:
            if queryset.first().nickname != nickName:
                queryset.update(nickname=nickName,update_time=datetime.datetime.now())
        if headImgUrl != None:
            if queryset.first().avatar != headImgUrl:
                queryset.update(avatar=headImgUrl,update_time=datetime.datetime.now())
        user_id = queryset.first().user_id
        nickName = queryset.first().nickname
        headImgUrl = queryset.first().avatar
    else:
        queryset = UserInfo.objects.create(
            open_id=open_id,
            avatar=headImgUrl,
            nickname=nickName
        )
        user_id = queryset.user_id
    package_id = 1
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    queryset = packageInfo.objects.filter(package_id=package_id).first()
    c = {
        'cores':queryset,
        'user_id':user_id,
        'open_id':open_id,
        'package_id':package_id
    }
    return render_to_response('package_detail.html',c)

# 私教试课
def trial_card_p(request):
    open_id = request.GET.get('openId')
    nickName = request.GET.get('nickName')
    headImgUrl = request.GET.get('headImgUrl')
    queryset = UserInfo.objects.filter(open_id=open_id)
    if queryset.exists():
        if nickName != None:
            if queryset.first().nickname != nickName:
                queryset.update(nickname=nickName,update_time=datetime.datetime.now())
        if headImgUrl != None:
            if queryset.first().avatar != headImgUrl:
                queryset.update(avatar=headImgUrl,update_time=datetime.datetime.now())
        user_id = queryset.first().user_id
        nickName = queryset.first().nickname
        headImgUrl = queryset.first().avatar
    else:
        queryset = UserInfo.objects.create(
            open_id=open_id,
            avatar=headImgUrl,
            nickname=nickName
        )
        user_id = queryset.user_id
    package_id = 11
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    queryset = packageInfo.objects.filter(package_id=package_id).first()
    c = {
        'cores':queryset,
        'user_id':user_id,
        'open_id':open_id,
        'package_id':package_id
    }
    return render_to_response('package_detail.html',c)

# 免费试课
def package_free(request):
    open_id = request.GET.get('openId')
    nickName = request.GET.get('nickName')
    headImgUrl = request.GET.get('headImgUrl')
    queryset = UserInfo.objects.filter(open_id=open_id)
    if queryset.exists():
        if nickName != None:
            if queryset.first().nickname != nickName:
                queryset.update(nickname=nickName,update_time=datetime.datetime.now())
        if headImgUrl != None:
            if queryset.first().avatar != headImgUrl:
                queryset.update(avatar=headImgUrl,update_time=datetime.datetime.now())
        user_id = queryset.first().user_id
        nickName = queryset.first().nickname
        headImgUrl = queryset.first().avatar
    else:
        queryset = UserInfo.objects.create(
            open_id=open_id,
            avatar=headImgUrl,
            nickname=nickName
        )
        user_id = queryset.user_id
    package_id = 12
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    queryset = packageInfo.objects.filter(package_id=package_id).first()
    c = {
        'cores':queryset,
        'user_id':user_id,
        'open_id':open_id,
        'package_id':package_id
    }
    return render_to_response('package_detail.html',c)

@csrf_exempt
def can_trial(request):
    open_id = request.POST.get('open_id')
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    package_id = request.POST.get('package_id')
    if int(package_id) == 1 or int(package_id) == 11:
        queryset = PayLog.objects.filter(user_id=user_id,package_id=package_id)
        if queryset.exists():
            return HttpResponse(package_id)

    return HttpResponse("ok")
 
# 返回用户中心
def center(request):
    open_id = request.GET.get('openId')
    nickName = request.GET.get('nickName')
    headImgUrl = request.GET.get('headImgUrl')

    queryset = UserInfo.objects.filter(open_id=open_id)
    if queryset.exists():
        if nickName != None:
            if queryset.first().nickname != nickName:
                queryset.update(nickname=nickName,update_time=datetime.datetime.now())
        if headImgUrl != None:
            if queryset.first().avatar != headImgUrl:
                queryset.update(avatar=headImgUrl,update_time=datetime.datetime.now())
        user_id = queryset.first().user_id
        nickName = queryset.first().nickname
        headImgUrl = queryset.first().avatar
    else:
        queryset = UserInfo.objects.create(
            open_id=open_id,
            avatar=headImgUrl,
            nickname=nickName
        )
        user_id = queryset.user_id
    c = {
        'user_id':user_id,
        'open_id':open_id,
        'nickName':nickName,
        'headImgUrl':headImgUrl
    }
    return render_to_response('center.html',c)

# 返回初始页面
def index(request):
    open_id = request.GET.get('open_id')
    c = {
        'open_id':open_id
    }
    return render_to_response('index.html',c)

# 返回支付页面
def pay(request):
    open_id = request.GET.get('open_id')
    package_id = request.GET.get('package_id')
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    queryset = packageInfo.objects.filter(package_id=package_id).first()

    order_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + str(user_id)
    print("==============================")
    print("==============================")
    print("==============================")
    print(order_id)
    print(datetime.datetime.now())
    query = NewPayLog.objects.create(
        user_id = user_id,
        package_id = package_id,
        order_id = order_id,
        price = queryset.price,
        amount = 1,
        status = 1,
        state = 1,
        create_time = datetime.datetime.now(),
        update_time = datetime.datetime.now()
    )
    c = {
        'cores':queryset,
        'user_id':user_id,
        'package_id':package_id,
        'open_id':open_id,
        'order_id':order_id,
        'query':query
    }
    return render_to_response('pay.html',c)

# @csrf_exempt
# def addclass(request):
#     user_id = request.POST.get('user_id')
#     return HttpResponse('true') 

# 根据open_id查询user_id，如果存在返回user_id
# 如果不存在，创建user_id并且返回
@csrf_exempt
def get_user_id(request):
    if request.method == 'POST':
        open_id = request.POST.get('open_id')
    else:
        open_id = request.GET.get('open_id')

    queryset = UserInfo.objects.filter(open_id=open_id)
    if queryset.exists():
        user_id = queryset.first().user_id
    else:
        log = UserInfo.objects.create(open_id=open_id)
        user_id = log.user_id
    return HttpResponse(user_id) 

# 返回用户套餐卡页面
def my_package(request):
    open_id = request.GET.get('openId')
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    queryset = user_package.objects.filter(user_id=user_id).all()
    cores = []
    a_json = []
    for qurey in queryset:
        print("=========================")
        print("=========================")
        print("=========================")
        print("=========================")
        expire_time = qurey.expire_time
        package_id = qurey.package_id
        print(package_id)

        core = packageInfo.objects.filter(package_id=package_id).first()
        a_json.append(
            {"package_name":core.package_name,
            "price":core.price,
            "status":qurey.status,
            "league_amount":qurey.league_amount,
            "private_amount":qurey.private_amount,
            "package_id":package_id,
            "expire_time":expire_time}
        )
    c = {
        'cores':a_json,
        'user_id':user_id,
        'open_id':open_id
    }
    return render_to_response('my_package.html',c)

# 返回用户预约课程
def my_class(request):
    open_id = request.GET.get('openId')
    nickName = request.GET.get('nickName')
    headImgUrl = request.GET.get('headImgUrl')
    queryset = UserInfo.objects.filter(open_id=open_id)
    if queryset.exists():
        if nickName != None:
            if queryset.first().nickname != nickName:
                queryset.update(nickname=nickName,update_time=datetime.datetime.now())
        if headImgUrl != None:
            if queryset.first().avatar != headImgUrl:
                queryset.update(avatar=headImgUrl,update_time=datetime.datetime.now())
        user_id = queryset.first().user_id
        nickName = queryset.first().nickname
        headImgUrl = queryset.first().avatar
    else:
        queryset = UserInfo.objects.create(
            open_id=open_id,
            avatar=headImgUrl,
            nickname=nickName
        )
        user_id = queryset.user_id

    c = {
        'open_id':open_id,
        'nickName':nickName,
        'headImgUrl':headImgUrl,
        'user_id':user_id
    }
    return render_to_response('my_class.html',c)

@csrf_exempt
def get_my_day_list(request):
    if request.method == 'POST':
        idx = request.POST.get('idx')
        open_id = request.POST.get('open_id')
    else:
        idx = request.GET.get('idx')
        open_id = request.GET.get('open_id')
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id

    today = now().date() + timedelta(days=(2*int(idx)))
    tomorrow = today + timedelta(days=2)
    # queryset = SchemeInfo.objects.filter(start_time__gte=today,start_time__lte=tomorrow).all().order_by("start_time")
    
    a_json=[]
    double_json=[]
    count = AppointInfo.objects.filter(user_id=user_id).all().count()
    # if count == 0:
    #     a_json.append({
    #         "day":noday,
    #         })
    #     double_json.append(a_json)
    #     return HttpResponse(json.dumps(double_json),content_type="application/json")
    center = (today + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
    center_tmp = (today + timedelta(days=1))
    center = center_tmp.strftime('%Y-%m-%d %H:%M:%S')
    print("=========================================================================")
    print(user_id)
    queryset = AppointInfo.objects.filter(start_time__gte=today,start_time__lte=tomorrow,user_id=user_id,status=1).all().order_by("start_time")
    if queryset.exists():
        for qry in queryset:
            print(queryset.first())
            print("==================================1=======================================")
            print(qry.scheme_id)
            query = SchemeInfo.objects.filter(scheme_id=qry.scheme_id).first()
            shijian = query.start_time.strftime('%Y-%m-%d %H:%M:%S')
            if shijian > center:
                double_json.append(a_json)
                # center = tomorrow.strftime('%Y-%m-%d')
                center_tmp = center_tmp + timedelta(days=1)
                center = center_tmp.strftime('%Y-%m-%d %H:%M:%S')
                a_json=[]
            user_name = UserInfo.objects.filter(user_id=(query.user_id)).first().nickname
            num = AppointInfo.objects.filter(scheme_id=(query.scheme_id),status=1).count()
            day = int(time.mktime(query.start_time.timetuple()))

            yuyue = AppointInfo.objects.filter(user_id=user_id,scheme_id=(query.scheme_id),status=1)
            isyueyue = 0
            if yuyue.exists():
                isyueyue = 1
                position = position_room.objects.filter(position_room_id=query.position).first().position_room_name
                a_json.append({
                    "day":day,
                    "scheme_id":query.scheme_id,
                    "scheme_name":query.scheme_name,
                    "user_name":user_name,
                    'now_people':num,
                    "max_people":query.max_people,
                    "isyuyue":isyueyue,
                    "position":position,
                    "type":query.scheme_type,
                    "count":count,
                })
            else:
                a_json.append({
                    "count":count
                })
        double_json.append(a_json)
    else:
        double_json.append({
            "count":count
        })
    
    # double_json.append(count)
    # return HttpResponse(json.dumps(a_json),content_type="application/json")
    return HttpResponse(json.dumps(double_json),content_type="application/json")

# 返回预约成功页面
def saoma(request):
    class_id = request.GET.get('class_id');
    open_id = request.GET.get('open_id');
    query = UserInfo.objects.filter(open_id=open_id).first()
    user_id = query.user_id
    nickname = query.nickname
    queryset = SchemeInfo.objects.filter(scheme_id=class_id).first()
    
    position = position_room.objects.filter(position_room_id=queryset.position).first().position_room_name
    c = {
        'cores':queryset,
        'class_id':class_id,
        'user_id':user_id,
        'open_id':open_id,
        'position':position,
        'nickname':nickname
    }
    return render_to_response('saoma.html',c)

# 返回二维码pay页面
def erweima_pay(request):
    user_id = request.GET.get('user_id')
    package_id = request.GET.get('package_id')
    queryset = packageInfo.objects.filter(package_id=package_id).first()
    c = {
        'cores':queryset,
        'user_id':user_id,
        'package_id':package_id
    }
    return render_to_response('erweima_pay.html',c)

# 返回教练中心
def teacher_center(request):
    open_id = request.GET.get('openId')
    nickName = request.GET.get('nickName')
    headImgUrl = request.GET.get('headImgUrl')

    queryset = UserInfo.objects.filter(open_id=open_id)
    if queryset.exists():
        if nickName != None:
            if queryset.first().nickname != nickName:
                queryset.update(nickname=nickName,update_time=datetime.datetime.now())
        if headImgUrl != None:
            if queryset.first().avatar != headImgUrl:
                queryset.update(avatar=headImgUrl,update_time=datetime.datetime.now())
        user_id = queryset.first().user_id
        nickName = queryset.first().nickname
        headImgUrl = queryset.first().avatar
    else:
        queryset = UserInfo.objects.create(
            open_id=open_id,
            avatar=headImgUrl,
            nickname=nickName
        )
        user_id = queryset.user_id
    c = {
        'open_id':open_id,
        'nickName':nickName,
        'headImgUrl':headImgUrl
    }
    query = UserInfo.objects.filter(open_id=open_id,user_type=0)
    if query.exists():
        return render_to_response('teacher_center.html',c)
    else:
        c={
        'open_id':open_id,
        'user_id':user_id
        }
        return render_to_response('teacher_tel.html',c)

@csrf_exempt
def teacher_tel(request):
    if request.method == 'POST':
        tel = request.POST.get('tel')
        open_id = request.POST.get('open_id')
    else:
        tel = request.GET.get('tel')
        open_id = request.GET.get('open_id')
    
    query_1 = UserInfo.objects.filter(open_id=open_id,user_type=1).first()
    queryset = UserInfo.objects.filter(tel=tel,user_type=0)
    if queryset.exists():
        if(queryset.first().open_id == ""):
            query = queryset.update(open_id=open_id,nickname=query_1.nickname,avatar=query_1.avatar,update_time=datetime.datetime.now())
            UserInfo.objects.filter(open_id=open_id,user_type=1).delete()
            query_1 = UserInfo.objects.filter(open_id=open_id,user_type=0).first()
            cores=[]
            cores.append({
                'open_id':query_1.open_id,
                'nickName':query_1.nickname,
                'headImgUrl':query_1.avatar,
                'user_id':query_1.user_id
            })
            return  HttpResponse(json.dumps(cores),content_type="application/json")
        else:
            # alert("该号码已被注册")
            return HttpResponse('1')
    else:
        # alert("该页面只为教练开放")
        return HttpResponse('2')

    return HttpResponse("3")

# 返回教练课程列表
def teacher_class_list(request):
    status = request.GET.get('status')
    open_id = request.GET.get('open_id')
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    end = request.GET.get('end')
    c = {
        'status':status,
        'user_id':user_id,
        'open_id':open_id,
        'end':end
    }

    return render_to_response('teacher_class_list.html',c)

@csrf_exempt
def get_teacher_day_list(request):
    if request.method == 'POST':
        idx = request.POST.get('idx')
        status = request.POST.get('status')
        open_id = request.POST.get('open_id')
        end = request.POST.get('end')
    else:
        idx = request.GET.get('idx')
        status = request.GET.get('status')
        open_id = request.GET.get('open_id')
        end = request.GET.get('end')

    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id

    if end == '0':
        if idx == '0':
            start_time = time.strftime('%Y-%m-%d %H:%M:%S')
            print(start_time)
        else:
            start_time = now().date() + timedelta(days=(2*int(idx)))

        today = now().date() + timedelta(days=(2*int(idx)))
        center = (today + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
        end_tmp = (today + timedelta(days=2)).strftime('%Y-%m-%d')
        end_time = (today + timedelta(days=2)).strftime('%Y-%m-%d %H:%M:%S')
       
        queryset = SchemeInfo.objects.filter(start_time__gte=start_time,start_time__lte=end_time,user_id=user_id,state=1).all().order_by("start_time")
    else:
        today = now().date() + timedelta(days=(2*int(idx)))
        start_time = (today + timedelta(days=-1)).strftime('%Y-%m-%d')
        start_time = (today + timedelta(days=-1)).strftime('%Y-%m-%d %H:%M:%S')
        center = today.strftime('%Y-%m-%d %H:%M:%S')
        end_tmp = time.strftime('%Y-%m-%d')
        end_time = time.strftime('%Y-%m-%d %H:%M:%S')
        queryset = SchemeInfo.objects.filter(start_time__gte=start_time,start_time__lte=end_time,user_id=user_id,status=status,state=1).all().order_by("-start_time")
    a_json=[]
    double_json=[]
    for query in queryset:
        shijian = query.start_time.strftime('%Y-%m-%d %H:%M:%S')
        if end == '0':
            if shijian > center:
                double_json.append(a_json)
                center = end_tmp
                a_json=[]
        else:
            if shijian < center:
                double_json.append(a_json)
                center = start_time
                a_json=[]
        user_name = UserInfo.objects.filter(user_id=(query.user_id)).first().real_name
        num = AppointInfo.objects.filter(scheme_id=(query.scheme_id),status=1).count()
        day = int(time.mktime(query.start_time.timetuple()))
        a_json.append({
            "day":day,
            "scheme_id":query.scheme_id,
            "scheme_name":query.scheme_name,
            "user_name":user_name,
            'now_people':num,
            "max_people":query.max_people,
        })
    double_json.append(a_json)
    return HttpResponse(json.dumps(double_json),content_type="application/json")


def teacher_stus(request):
    class_id = request.GET.get('class_id')
    open_id = request.GET.get('open_id')

    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    start_time = SchemeInfo.objects.filter(scheme_id=class_id).first().start_time.strftime('%Y-%m-%d %H:%M:%S')
    
    c = {
        'user_id':user_id,
        'open_id':open_id,
        'class_id':class_id,
        'start_time':start_time
    }
    return render_to_response('teacher_stus.html',c)

@csrf_exempt
def get_teacher_stus(request):
    if request.method == 'POST':
        class_id = request.POST.get('class_id')
        open_id = request.POST.get('open_id')
    else:
        class_id = request.GET.get('class_id')
        open_id = request.GET.get('open_id')
    
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    queryset = AppointInfo.objects.filter(scheme_id=class_id,status=1).all()
    a_json = []
    for query in queryset:
        qry = UserInfo.objects.filter(user_id=(query.user_id)).first()
        a_json.append({
            "user_name":qry.nickname,
            "user_id":query.user_id
        })
    return HttpResponse(json.dumps(a_json),content_type="application/json")
@csrf_exempt
def get_teacher_stus_all(request):
    if request.method == 'POST':
        class_id = request.POST.get('class_id')
        open_id = request.POST.get('open_id')
    else:
        class_id = request.GET.get('class_id')
        open_id = request.GET.get('open_id')

    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    queryset = AppointInfo.objects.filter(scheme_id=class_id,status=2).all()
    a_json = []
    for query in queryset:
        qry = UserInfo.objects.filter(user_id=(query.user_id)).first()
        a_json.append({
            "user_name":qry.nickname,
            "user_id":query.user_id
        })
    return HttpResponse(json.dumps(a_json),content_type="application/json")

@csrf_exempt
def return_t_stu(request):
    arr = request.POST.get('arr')
    cores = re.split(',',arr)
    for core in cores:
        print(core)
        tijiao = AppointInfo.objects.filter(user_id=core).update(status=2,update_time=datetime.datetime.now())
    return HttpResponse("hh")
@csrf_exempt
def yuyue(request):
    if request.method == 'POST':
        class_id = request.POST.get('class_id')
        open_id = request.POST.get('open_id')
    else:
        class_id = request.GET.get('class_id')
        open_id = request.GET.get('open_id')
    
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id

    today = now().date()

    qry = SchemeInfo.objects.filter(scheme_id=class_id).first()
    class_type = qry.scheme_type
    cut = AppointInfo.objects.filter(scheme_id=class_id,status=1).count()
    max_cut = qry.max_people
    if cut < int(max_cut):
        queryset = user_package.objects.filter(user_id=user_id,expire_time__gte=today)
        if queryset.exists():
            user_package_all = user_package.objects.filter(user_id=user_id).all()
            for query in user_package_all:
                if int(query.status) == 1:
                    count =  (query.league_amount) if (int(class_type) == 0) else (query.private_amount)
                    if int(count) > 0:
                        # 预约成功，套餐卡使用记录加一条，预约表加一条，用户套餐卡表次数减少
                        yuyue = used_log.objects.create(
                                                    user_id=user_id,
                                                    user_package_id=query.user_package_id,
                                                    scheme_id=class_id,
                                                    scheme_type=1,
                                                    status=1,
                                                    state=1
                                                )
                        yuyue_2 = AppointInfo.objects.create(
                                user_id = user_id,
                                scheme_id = class_id,
                                start_time = qry.start_time,
                                status = 1,
                                state = 1
                            )
                        if int(class_type) == 1:
                            yuyue_3 = user_package.objects.filter(user_package_id=query.user_package_id).update(private_amount=(int(query.private_amount)-1),update_time=datetime.datetime.now())
                        else:
                            yuyue_3 = user_package.objects.filter(user_package_id=query.user_package_id).update(league_amount=(int(query.league_amount)-1),update_time=datetime.datetime.now())
                        return HttpResponse('true')
        return HttpResponse('false')
    else:
        return HttpResponse('none')

@csrf_exempt
def unyuyue(request):
    if request.method == 'POST':
        class_id = request.POST.get('class_id')
        open_id = request.POST.get('open_id')
    else:
        class_id = request.GET.get('class_id')
        open_id = request.GET.get('open_id')

    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    # 取消预约，套餐卡使用记录改状态，预约表改状态，用户套餐卡次数增加
    queryset = used_log.objects.filter(user_id=user_id,scheme_id=class_id).first()
    user_package_id = queryset.user_package_id
    class_type = queryset.scheme_type
    unyuyue_1 = used_log.objects.filter(user_id=user_id,scheme_id=class_id).update(status=0,update_time=datetime.datetime.now())
    unyuyue_2 = AppointInfo.objects.filter(user_id=user_id,scheme_id=class_id).update(status=0,update_time=datetime.datetime.now())
    query = user_package.objects.filter(user_package_id=user_package_id).first()
    if int(class_type) == 0:
        yuyue_3 = user_package.objects.filter(user_package_id=user_package_id).update(private_amount=(int(query.private_amount)+1),update_time=datetime.datetime.now())
    else:
        yuyue_3 = user_package.objects.filter(user_package_id=user_package_id).update(league_amount=(int(query.league_amount)+1),update_time=datetime.datetime.now())
    return HttpResponse('true')
    
@csrf_exempt
def addpackage(request):
    open_id = request.POST.get('open_id')
    pay_type = request.POST.get("pay_type")
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    package_id = request.POST.get('package_id')
    status = request.POST.get('status')
    queryset = packageInfo.objects.filter(package_id=package_id).first()
    expire_time = now().date() + timedelta(days=queryset.valid_days)
    new_pay = PayLog.objects.create(
            user_id = user_id,
            package_id = package_id,
            amount = 1,
            price = queryset.price,
            status = status,
            state = 1,
            pay_type = pay_type
        )
    user_pay = user_package.objects.create(
        user_id = user_id,
        package_id = package_id,
        league_amount = queryset.league_amount,
        private_amount = queryset.private_amount,
        expire_time = expire_time,
        status = status,
        state = 1,
        pay_type = pay_type,
        )
    tel = UserInfo.objects.filter(open_id=open_id).first().tel
    if tel == None or tel == '':
        return HttpResponse('false')
    else:
        return HttpResponse('true')



def pc_index(request):
    queryset = user_package.objects.filter(status=2)
    cores = []
    if queryset.exists():
        for query in queryset:
            query_1 = UserInfo.objects.filter(user_id=query.user_id).first()
            query_2 = packageInfo.objects.filter(package_id=query.package_id).first()
            name = query_1.real_name
            if name is None or name == '':
                name = query_1.nickname
            cores.append({
                "user_name":name,
                "user_id":query_1.user_id,
                "tel":query_1.tel,
                "package_name":query_2.package_name,
                "price":query_2.price,
                "create_time":query.create_time,
                "user_package_id":query.user_package_id
                })

    c = {
        'cores':cores
    }

    return render_to_response('pc_index.html',c)

def pc_position(request):
    return render_to_response('pc_position.html')

def pc_teacher(request):
    return render_to_response('pc_teacher.html')

def pc_class(request):
    return render_to_response('pc_class.html')

@csrf_exempt
def pc_look(request):
    user_package_id = request.POST.get('user_package_id')
    user_id = request.POST.get('user_id')
    flag = request.POST.get('flag')
    look = user_package.objects.filter(user_package_id=user_package_id,user_id=user_id).update(status=flag,update_time=datetime.datetime.now())
    return HttpResponse('true')


# 返回套餐卡详情
def my_package_info(request):
    open_id = request.GET.get('open_id')
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    package_id = request.GET.get('package_id')
    queryset = packageInfo.objects.filter(package_id=package_id).first()
    c = {
        'cores':queryset,
        'user_id':user_id,
        'package_id':package_id,
        'open_id':open_id
    }
    return render_to_response('my_package_info.html',c)

def header(request):
    return render_to_response('header.html')


# 这段还没写好
def position_info(request):
    open_id = request.GET.get("open_id")
    position_id = request.GET.get("position_id")
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id
    isimg = []
    queryset = position_room.objects.filter(position_room_id=position_id).first()
    img_url = position_img.objects.filter(position_room_id=position_id).first().img_url
    c = {
        'cores':queryset,
        'user_id':user_id,
        'open_id':open_id,
        'img_url':img_url
    }

    return render_to_response('position_info_tmp.html',c)

def teacher_info(request):
    open_id = request.GET.get("open_id")
    teacher_id = request.GET.get("teacher_id")
    user_id = UserInfo.objects.filter(open_id=open_id).first().user_id

    queryset = UserInfo.objects.filter(user_id=teacher_id).first()

    img_url = teacher_img.objects.filter(user_id=teacher_id,status=1).first().img_url
    c = {
        'cores':queryset,
        'user_id':user_id,
        'open_id':open_id,
        'img_url':img_url
    }

    return render_to_response('teacher_info.html',c)

@csrf_exempt
def pc_index_get_appoint(request):
    if request.method == 'POST':
        stime = request.POST.get("stime")
        etime_tmp = request.POST.get("etime")
    else:
        stime = request.GET.get("stime")
        etime_tmp = request.GET.get("etime")

    etime = datetime.datetime.strptime(etime_tmp,'%Y-%m-%d') + timedelta(days=1)
    queryset = user_package.objects.filter(pay_type=0,create_time__gte=stime,create_time__lte=etime).order_by("create_time")
    cores = []
    if queryset.exists():
        for query in queryset:
            query_1 = UserInfo.objects.filter(user_id=query.user_id).first()
            query_2 = packageInfo.objects.filter(package_id=query.package_id).first()
            name = query_1.real_name
            if name is None or name == '':
                name = query_1.nickname
            cores.append({
                "user_name":name,
                "tel":query_1.tel,
                "package_name":query_2.package_name,
                "price":float(query_2.price),
                "create_time":query.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                "update_time":query.update_time.strftime('%Y-%m-%d %H:%M:%S'),
                "user_package_id":query.user_package_id,
                "status":query.status,
                })
    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")



# paylog 表里，status=2 代表已经未支付完成，1代表已经支付完成
@csrf_exempt
def pc_index_order(request):
    user_package_id = request.POST.get('user_package_id')
    status = int(request.POST.get('status'))

    if status == 1:
        status = 2
    else:
        status = 1
    look = user_package.objects.filter(user_package_id=user_package_id).update(status=status,update_time=datetime.datetime.now())
    # 暂时不去修改paylog表，所有查询支付的，都从user_package里面找
    # look_1 = PayLog.objects.filter().update(status=1,update_time=datetime.datetime.now())
    return HttpResponse('true')




@csrf_exempt
def pc_package_get_package(request):
    # stime = request.POST.get("stime")
    # etime_tmp = request.POST.get("etime")
    # etime = datetime.datetime.strptime(etime_tmp,'%Y-%m-%d') + timedelta(days=1)
    # queryset = user_package.objects.filter(pay_type=0,create_time__gte=stime,create_time__lte=etime).order_by("create_time")
    queryset = packageInfo.objects.all()
    cores = []
    if queryset.exists():
        for query in queryset:
            cores.append({
                "package_id":query.package_id,
                "package_name":query.package_name,
                "league_amount":query.league_amount,
                "private_amount":query.private_amount,
                "introduce":query.introduce,
                "price":float(query.price),
                "status":query.status,
                "state":query.state,
                "valid_days":query.valid_days,
                "create_time":query.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                "update_time":query.update_time.strftime('%Y-%m-%d %H:%M:%S'),
                })

    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")

@csrf_exempt
def pc_package_get_single_package(request):
    package_id = request.POST.get("id")
    query = packageInfo.objects.filter(package_id=package_id).first()
    cores = {
        "package_id":query.package_id,
        "package_name":query.package_name,
        "league_amount":query.league_amount,
        "private_amount":query.private_amount,
        "introduce":query.introduce,
        "price":float(query.price),
        "status":query.status,
        "state":query.state,
        "valid_days":query.valid_days,
        "create_time":query.create_time.strftime('%Y-%m-%d %H:%M:%S'),
        "update_time":query.update_time.strftime('%Y-%m-%d %H:%M:%S'),
        }
    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")

@csrf_exempt
def pc_add_package(request):
    package_name = request.POST.get("package_name")
    league_amount = request.POST.get("league_amount")
    private_amount = request.POST.get("private_amount")
    introduce = request.POST.get("introduce")
    price = request.POST.get("price")
    valid_days = request.POST.get("valid_days")
    status = request.POST.get("status")
    state = request.POST.get("state")

    queryset = packageInfo.objects.create(
        package_name = package_name,
        league_amount = league_amount,
        private_amount = private_amount,
        introduce = introduce,
        price = price,
        valid_days = valid_days,
        status = status,
        state = state,
    )
    return HttpResponse(json.dumps({"errMsg":"success"}),content_type="application/json")


@csrf_exempt
def pc_xiugai_package(request):
    package_id = request.POST.get("uid")
    package_name = request.POST.get("package_name")
    league_amount = request.POST.get("league_amount")
    private_amount = request.POST.get("private_amount")
    introduce = request.POST.get("introduce")
    price = request.POST.get("price")
    valid_days = request.POST.get("valid_days")
    status = request.POST.get("status")
    state = request.POST.get("state")

    queryset = packageInfo.objects.filter(package_id=package_id).update(
        package_name = package_name,
        league_amount = league_amount,
        private_amount = private_amount,
        introduce = introduce,
        price = price,
        valid_days = valid_days,
        status = status,
        state = state,
        update_time=datetime.datetime.now()
    )
    return HttpResponse(json.dumps({"errMsg":"success"}),content_type="application/json")




@csrf_exempt
def pc_position_get_position(request):
    # stime = request.POST.get("stime")
    # etime_tmp = request.POST.get("etime")
    # etime = datetime.datetime.strptime(etime_tmp,'%Y-%m-%d') + timedelta(days=1)
    # queryset = user_package.objects.filter(pay_type=0,create_time__gte=stime,create_time__lte=etime).order_by("create_time")
    queryset = position_room.objects.all()
    cores = []
    if queryset.exists():
        for query in queryset:
            queryset_1 = position_img.objects.filter(position_room_id=query.position_room_id,states=1).all()
            imgs = []
            for query_1 in queryset_1:
                imgs.append({"url":query_1.img_url})
            cores.append({
                "position_room_id":query.position_room_id,
                "position_room_name":query.position_room_name,
                "introduce":query.introduce,
                "img_url":imgs,
                "create_time":query.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                "update_time":query.update_time.strftime('%Y-%m-%d %H:%M:%S'),
                })

    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")

@csrf_exempt
def pc_position_get_single_position(request):
    if request.method == 'POST':
        position_room_id = request.POST.get("id")
    else:
        position_room_id = request.GET.get("id")
    query = position_room.objects.filter(position_room_id=position_room_id).first()
  
    queryset_1 = position_img.objects.filter(position_room_id=query.position_room_id,states=1).all()
    imgs = []
    for query_1 in queryset_1:
        imgs.append({
            "position_img_id":query_1.position_img_id,
            "url":query_1.img_url,
            })
    cores = {
        "position_room_id":query.position_room_id,
        "position_room_name":query.position_room_name,
        "introduce":query.introduce,
        "img_url":imgs,
        "create_time":query.create_time.strftime('%Y-%m-%d %H:%M:%S'),
        "update_time":query.update_time.strftime('%Y-%m-%d %H:%M:%S'),
        }
    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")

@csrf_exempt
def pc_add_position(request):
    position_room_name = request.POST.get("position_room_name")
    introduce = request.POST.get("introduce")
    img_url = request.POST.get("img_url")
    imgs = re.split(';',img_url)

    queryset = position_room.objects.create(
        position_room_name = position_room_name,
        introduce = introduce
    )

    for img in imgs:
        if img is None or img == '':
            pass
        else:
            query = position_img.objects.create(
                position_room_id = queryset.position_room_id,
                img_url = img,
                states=1,
                status=1,
            )
    return HttpResponse(json.dumps({"errMsg":"success"}),content_type="application/json")


@csrf_exempt
def pc_xiugai_position(request):
    position_room_id = request.POST.get("uid")
    position_room_name = request.POST.get("position_room_name")
    introduce = request.POST.get("introduce")
    img_url = request.POST.get("img_url")
    imgs = re.split(';',img_url)

    queryset = position_room.objects.filter(position_room_id=position_room_id).update(
        position_room_name = position_room_name,
        introduce = introduce,
        update_time=datetime.datetime.now()
    )
    querys = position_img.objects.filter(position_room_id=position_room_id).all().update(states=0,update_time=datetime.datetime.now())
    for img in imgs:
        if img is None or img == '':
            pass
        else:
            query = position_img.objects.create(
                position_room_id = position_room_id,
                img_url = img,
                states = 1,
                status = 1
            )
    return HttpResponse(json.dumps({"errMsg":"success"}),content_type="application/json")

@csrf_exempt
def pc_teacher_get_teacher(request):
    queryset = UserInfo.objects.filter(user_type=0).all()
    cores = []
    if queryset.exists():
        for query in queryset:
            queryset_1 = teacher_img.objects.filter(user_id=query.user_id,status=1,states=1).all()
            imgs = []
            for query_1 in queryset_1:
                imgs.append({"url":query_1.img_url})
            cores.append({
                "user_id":query.user_id,
                "real_name":query.real_name,
                "tel":query.tel,
                "introduce":query.detail_introduce,
                "status":query.status,
                "img_url":imgs,
                })

    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")

@csrf_exempt
def pc_teacher_get_single_teacher(request):
    if request.method == 'POST':
        user_id = request.POST.get("id")
    else:
        user_id = request.GET.get("id")

    query = UserInfo.objects.filter(user_id=user_id,user_type=0).first()
    queryset_1 = teacher_img.objects.filter(user_id=user_id,status=1,states=1).all()
    imgs = []
    for query_1 in queryset_1:
        imgs.append({"url":query_1.img_url})

    cores = {
        "real_name":query.real_name,
        "tel":query.tel,
        "introduce":query.detail_introduce,
        "status":query.status,
        "img_url":imgs,
        }
    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")




@csrf_exempt
def pc_add_teacher(request):
    real_name = request.POST.get("real_name")
    tel = request.POST.get("tel")
    introduce = request.POST.get("introduce")
    status = request.POST.get("status")
    img_url = request.POST.get("img_url")
    imgs = re.split(';',img_url)

    queryset = UserInfo.objects.create(
        real_name = real_name,
        tel = tel,
        detail_introduce = introduce,
        status = status,
        user_type = 0,
        state = 1,
    )

    for img in imgs:
        if img is None or img == '':
            pass
        else:
            query = teacher_img.objects.create(
                user_id = queryset.user_id,
                img_url = img,
                states = 1,
                status = 1
            )
    return HttpResponse(json.dumps({"errMsg":"success"}),content_type="application/json")

@csrf_exempt
def pc_xiugai_teacher(request):
    user_id = request.POST.get("uid")
    real_name = request.POST.get("real_name")
    tel = request.POST.get("tel")
    introduce = request.POST.get("introduce")
    status = request.POST.get("status")
    img_url = request.POST.get("img_url")
    imgs = re.split(';',img_url)

    queryset = UserInfo.objects.filter(user_id=user_id).update(
        real_name = real_name,
        tel = tel,
        detail_introduce = introduce,
        status = status,
        user_type = 0,
        state = 1,
        update_time=datetime.datetime.now()
    )

    querys = teacher_img.objects.filter(user_id=user_id).all().update(states=0,update_time=datetime.datetime.now())

    for img in imgs:
        if img is None or img == '':
            pass
        else:
            query = teacher_img.objects.filter(user_id=user_id).create(
                user_id = user_id,
                img_url = img,
                states = 1,
                status = 1
            )
    return HttpResponse(json.dumps({"errMsg":"success"}),content_type="application/json")






@csrf_exempt
def pc_class_get_class(request):
    stime = request.POST.get("stime")
    etime = request.POST.get("etime")
    # 获取起始时间内的所有课程
    class_queryset = SchemeInfo.objects.filter(start_time__gte=stime,start_time__lte=etime).all().order_by("start_time")
    cores = []
    if class_queryset.exists():
        # 循环所有课程，拼接课程信息进去
        for class_query in class_queryset:
            user_query = UserInfo.objects.filter(user_id=class_query.user_id).first()
            appoint_count = AppointInfo.objects.filter(scheme_id=class_query.scheme_id,status=1).count()
            position_room_name = position_room.objects.filter(position_room_id=class_query.position).first().position_room_name
            
            cores.append({
                "class_id":class_query.scheme_id,
                "class_name":class_query.scheme_name,
                "user_id":class_query.user_id,
                "real_name":user_query.real_name,
                "introduce":class_query.introduce,
                "start_time":class_query.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                "con_time":class_query.continue_time,
                "appoint_count":appoint_count,
                "max_count":class_query.max_people,
                "class_type":class_query.scheme_type,
                "position_id":class_query.position,
                "position_room_name":position_room_name,
                "status":class_query.status,
                "state":class_query.state,
                })

    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")

@csrf_exempt
def pc_class_get_single_class(request):
    if request.method == 'POST':
        class_id = request.POST.get("id")
    else:
        class_id = request.GET.get("id")

    class_query = SchemeInfo.objects.filter(scheme_id=class_id).first()

    user_query = UserInfo.objects.filter(user_id=class_query.user_id).first()
    appoint_count = AppointInfo.objects.filter(scheme_id=class_query.scheme_id).count()
    position_room_name = position_room.objects.filter(position_room_id=class_query.position).first().position_room_name
    
    cores = {
        "class_id":class_query.scheme_id,
        "class_name":class_query.scheme_name,
        "user_id":class_query.user_id,
        "real_name":user_query.real_name,
        "introduce":class_query.introduce,
        "start_time":class_query.start_time.strftime('%Y-%m-%d %H:%M:%S'),
        "con_time":class_query.continue_time,
        "appoint_count":appoint_count,
        "max_count":class_query.max_people,
        "class_type":class_query.scheme_type,
        "position_id":class_query.position,
        "position_room_name":position_room_name,
        "status":class_query.status,
        "state":class_query.state,
        }

    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")

def pc_class_get_single_init(request):
    t_queryset = UserInfo.objects.filter(user_type=0,status=0).all().order_by("real_name")
    p_queryset = position_room.objects.all()
    t_sel = []
    p_sel = []
    for t_query in t_queryset:
        t_sel.append({
            "user_id":t_query.user_id,
            "real_name":t_query.real_name,
        })
    for p_query in p_queryset:
        p_sel.append({
            "position_room_id":p_query.position_room_id,
            "position_room_name":p_query.position_room_name,
        })

    jsons = json.dumps({"data":{"t_sel":t_sel,"p_sel":p_sel},"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")




@csrf_exempt
def pc_add_class(request):
    class_name = request.POST.get("class_name")
    introduce = request.POST.get("introduce")
    start_time = request.POST.get("start_time")
    con_time = request.POST.get("con_time")
    max_count = request.POST.get("max_count")
    class_type = request.POST.get("class_type")
    state = request.POST.get("state")
    real_name = request.POST.get("real_name")
    position_id = request.POST.get("position_id")

    c_query = SchemeInfo.objects.create(
        scheme_name = class_name,
        user_id = real_name,
        introduce = introduce,
        start_time = start_time,
        continue_time = con_time,
        max_people = max_count,
        scheme_type = class_type,
        status = 1,
        state = state,
        position = position_id
    )
    
    return HttpResponse(json.dumps({"errMsg":"success"}),content_type="application/json")

@csrf_exempt
def pc_xiugai_class(request):
    class_id = request.POST.get("uid")
    class_name = request.POST.get("class_name")
    introduce = request.POST.get("introduce")
    start_time = request.POST.get("start_time")
    con_time = request.POST.get("con_time")
    max_count = request.POST.get("max_count")
    class_type = request.POST.get("class_type")
    state = request.POST.get("state")
    real_name = request.POST.get("real_name")
    position_id = request.POST.get("position_id")

    c_query = SchemeInfo.objects.filter(scheme_id=class_id).update(
        scheme_name = class_name,
        user_id = real_name,
        introduce = introduce,
        start_time = start_time,
        continue_time = con_time,
        max_people = max_count,
        scheme_type = class_type,
        status = 1,
        state = state,
        position = position_id,
        update_time=datetime.datetime.now()
    )
    
    return HttpResponse(json.dumps({"errMsg":"success"}),content_type="application/json")

@csrf_exempt
def pc_class_get_student(request):
    class_id = request.POST.get("id")

    appoint_queryset = AppointInfo.objects.filter(scheme_id=class_id,status=1).all()
    cores = []
    for appoint_query in appoint_queryset:
        user_query = UserInfo.objects.filter(user_id=appoint_query.user_id).first()
        cores.append({
            "real_name":user_query.real_name,
            "nickname":user_query.nickname,
            "tel":user_query.tel,
        })
    
    jsons = json.dumps({"data":cores,"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")

@csrf_exempt
def login(request):
    phone = request.POST.get('phone')
    password = request.POST.get('password')

    query = user_base.objects.filter(userName=phone,password=password,state=1)
    cores = []
    cores.append({
        "name":phone,
        "pwd":password,
        "brand":2,
        "brandaddress":"上海浦东新区",
        "brandname":"柳瑜伽",
        "city":44,
        "cityaddress":"上海市某区某路千叶总店",
        "cityname":"上海市市辖区",
        "id":344,
        "name":"柳瑜伽总部",
        "phone":phone,
        "province":6,
        "provincename":"上海",
        "role":"admin",
        "state":"1",
        "store":1,
        "storeaddress":"100",
        "storename":"柳瑜伽总部",
        "storeparent":0,
        "storephone":"",
        "storetype":2,
    })
    if query.exists():
        return HttpResponse(json.dumps({"errCode":"success","data":cores}),content_type="application/json")
    else:
        return HttpResponse(json.dumps({"errCode":3}),content_type="application/json")

@csrf_exempt
def change_pwd(request):
    phone = request.POST.get('phone')
    password = request.POST.get('password')
    query = user_base.objects.filter(userName=phone).update(password=password,update_time=datetime.datetime.now())
    return HttpResponse(json.dumps({"errMsg":"success"}),content_type="application/json")


@csrf_exempt
def baobiao(request):
    stime = request.POST.get("stime")
    etime_tmp = request.POST.get("etime")
    etime = datetime.datetime.strptime(etime_tmp,'%Y-%m-%d') + timedelta(days=1)

    pay_type = request.POST.get("pay_type")

    if pay_type == "all":
        queryset = user_package.objects.filter(create_time__gte=stime,create_time__lte=etime,status=1).order_by("create_time")
    else:
        queryset = user_package.objects.filter(pay_type=pay_type,status=1,create_time__gte=stime,create_time__lte=etime).order_by("create_time")
    
    cores = []
    count = 0
    if queryset.exists():
        for query in queryset:
            query_1 = UserInfo.objects.filter(user_id=query.user_id).first()
            query_2 = packageInfo.objects.filter(package_id=query.package_id).first()
            count = count + query_2.price
            name = query_1.real_name
            if name is None or name == '':
                name = query_1.nickname
            cores.append({
                "user_name":name,
                "tel":query_1.tel,
                "package_name":query_2.package_name,
                "price":float(query_2.price),
                "create_time":query.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                "update_time":query.update_time.strftime('%Y-%m-%d %H:%M:%S'),
                "user_package_id":query.user_package_id,
                "status":query.status,
                "count":float(count)
                })

    jsons = json.dumps({"data":cores,"errMsg":"success"})
    # jsons = json.dumps({"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")





@csrf_exempt
def baobiao_2(request):
    query = AppointInfo.objects.filter(status=(1,2))
    return( '')
    stime = request.POST.get("stime")
    etime_tmp = request.POST.get("etime")
    etime = datetime.datetime.strptime(etime_tmp,'%Y-%m-%d') + timedelta(days=1)

    position_id = request.POST.get("position_id")
    teacher_id = request.POST.get("teacher_id")
    class_type = request.POST.get("class_type")




    jsons = json.dumps({"class_yuyue":class_yuyue,"class_num":"class_num"})
    # jsons = json.dumps({"errMsg":"success"})
    return HttpResponse(jsons,content_type="application/json")



 


































































































